package cn.app.web.shiro;

import java.util.Arrays;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import cn.app.dao.devuser.DevUserDao;
import cn.app.entity.DevUser;

public class CustomRealm extends AuthorizingRealm{
	
	@Autowired
	private DevUserDao devUserDao;
	
	@Override
	public String getName() {
		return "CustomRealm";
	}
	
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(
			AuthenticationToken token) throws AuthenticationException {
		//获得用户名
		String devcode = (String) token.getPrincipal();
		
		//根据用户名去数据库查询
		DevUser devUser = devUserDao.findDevUserByDevCode(devcode);
		if(devUser == null){
			return null;
		}
		/*
		 * 挺好玩..
		 * String devpassword = devUser.getDevpassword();
		Object credentials = token.getCredentials();
		char[] c = (char[]) credentials;
		String password = "";
		for (int i = 0; i < c.length; i++) {
			password += c[i]+"";
		}
		if(devpassword.equals(password)){
			SecurityUtils.getSubject().getSession().setAttribute("devUser", devUser);
		}*/
		SecurityUtils.getSubject().getSession().setAttribute("devUser", devUser);
		
		
		return new SimpleAuthenticationInfo(devUser.getDevcode(),devUser.getDevpassword(),getName());
	}
	
	
	
	
	
	
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(
			PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

	
	
}
